#include "header.h"

extern jpeg_header jpeg_header_info;
uint8_t *read_jpeg_file(char *filename){
    uint8_t *raw_image;
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;

    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_decompress(&cinfo);
    FILE * infile;
    if ((infile = fopen(filename, "rb")) == NULL) {
	 fprintf(stderr, "can't open file %s\n to read", filename);
	 exit(1);
    }
    jpeg_stdio_src(&cinfo, infile);
    jpeg_read_header(&cinfo, TRUE);
    jpeg_start_decompress(&cinfo);
    JSAMPROW row_pointer[1];
    row_pointer[0]=(uint8_t *)malloc( cinfo.output_width*cinfo.num_components );
    raw_image = (uint8_t*)malloc( cinfo.output_width*cinfo.output_height*cinfo.num_components );
    unsigned long location =0;
    int i;
    while( cinfo.output_scanline < cinfo.image_height )
    {
        jpeg_read_scanlines( &cinfo, row_pointer, 1 );
        for( i=0; i<cinfo.image_width*cinfo.num_components;i++)
            raw_image[location++] = row_pointer[0][i];
    }
    
    jpeg_finish_decompress( &cinfo );
    jpeg_destroy_decompress( &cinfo );
    free( row_pointer[0] );
    fclose( infile );
    return raw_image;
}


void write_jpeg_file(char *filename, int quality,uint8_t *plane){
   struct jpeg_compress_struct cinfo;
   struct jpeg_error_mgr jerr;
   cinfo.err = jpeg_std_error(&jerr);
   jpeg_create_compress(&cinfo);
   FILE *outfile;
   if((outfile=fopen(filename,"wb"))==NULL){
       fprintf(stderr,"can't open file %s to write\n ",filename);
       exit(1);
   }
   jpeg_stdio_dest(&cinfo, outfile);
   cinfo.image_width = jpeg_header_info.width; 	/* image width and height, in pixels */
   cinfo.image_height = jpeg_header_info.height;
   cinfo.input_components = jpeg_header_info.num_components;	/* # of color components per pixel */
   cinfo.in_color_space = jpeg_header_info.color_space; /* colorspace of input image */
   jpeg_set_defaults(&cinfo);
   cinfo.dct_method = JDCT_FLOAT;
   jpeg_set_quality(&cinfo, quality, TRUE);
   jpeg_start_compress(&cinfo, TRUE);
   JSAMPROW row_pointer[1];
   while(cinfo.next_scanline < cinfo.image_height){
	 row_pointer[0] = &plane[ cinfo.next_scanline * cinfo.image_width * cinfo.input_components];
	 jpeg_write_scanlines(&cinfo, row_pointer, 1);
   }
   jpeg_finish_compress(&cinfo);
   fclose(outfile);
   jpeg_destroy_compress(&cinfo);
}



